package com.example.myapplication

import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.ui.Modifier
import androidx.core.content.ContextCompat
import com.example.myapplication.ui.theme.MyApplicationTheme
import com.hoho.android.usbserial.driver.CdcAcmSerialDriver
import com.hoho.android.usbserial.driver.UsbSerialPort
import com.hoho.android.usbserial.driver.UsbSerialProber
import com.hoho.android.usbserial.util.SerialInputOutputManager
import kotlin.concurrent.thread


class CdcUsbActivity : ComponentActivity() {
    private lateinit var usbManager: UsbManager
    private var usbDevice: UsbDevice? = null
    private var serialPort: UsbSerialPort? = null

    var ACTION_USB_PERMISSION2 = "android.permission.USB_PERMISSION"

    val TIMEOUT = 1000

    val ACTION_USB_PERMISSION: String = "com.example.myapplication.GRANT_USB"

    val INTENT_ACTION_GRANT_USB: String = "com.example.myapplication.INTENT_ACTION_GRANT_USB"

    override fun onDestroy() {
        super.onDestroy()
        serialPort?.close()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            MyApplicationTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) {innerPadding ->
                    com.example.myapplication.Greeting(
                        name = "222",
                        modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }
        usbManager = getSystemService(Context.USB_SERVICE) as UsbManager

        Log.e("onCreate","size"+usbManager.deviceList.size)
        // 注册 USB 状态监听
//        registerReceiver(usbReceiver, IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED))

//        registerReceiver(usbPermissionReceiver, IntentFilter(ACTION_USB_PERMISSION))
        registerUsbReceiver()


        // Find all available drivers from attached devices.
        val manager = getSystemService(USB_SERVICE) as UsbManager
        val availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager)
        if (availableDrivers.isEmpty()) {
            return
        }

        // Open a connection to the first available driver.
        val driver = availableDrivers.get(0)
        Log.e("!!！！！！!driver",""+driver.toString())
        val device = driver.getDevice()
        val connection = manager.openDevice(device)
        Log.e("!!！！！！!connection",""+connection.toString())
        if (connection == null) {
            // add UsbManager.requestPermission(driver.getDevice(), ..) handling here
            val permissionIntent = PendingIntent.getBroadcast(
                this, 0, Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE
            )
            usbManager.requestPermission(device, permissionIntent)
            return
        }

        val port = driver.getPorts().get(0) // Most devices have just one port (port 0)
        port.open(connection)

        //TEST
        for (port in driver.ports){
            Log.e("!!!TEST", "portNumber:"+ port.portNumber)
//            Log.e("!!!TEST", "serial:"+ port)
            Log.e("!!!TEST", "isOpen:"+ port.isOpen)
        }

//        port.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE)
        port.setDTR(true); // for arduino, ...
//        port.setRTS(true);
        Log.e("!!!TEST", "DTR:"+ port.dtr)
        val usbIoManager = SerialInputOutputManager(port, object: SerialInputOutputManager.Listener{
            override fun onNewData(data: ByteArray) {
                Log.e("!!!onNewData", String(data, Charsets.UTF_8))
            }

            override fun onRunError(e: Exception?) {
                Log.e("!!!onRunError", e?.message.toString())
            }

        })
        usbIoManager.start()
//        usbIoManager.writeAsync()
        val data = """{"cmd":"sys_info"}"""
        port.write(data.toByteArray(), 0)
        port.write("\n".toByteArray(), 0)

//        thread {
////            val data = """{"cmd":"sys_info"}"""
////            port.write(data.toByteArray(), 0)
////            port.write("\n".toByteArray(), 0)
////
////            Log.e("!!!port.write", data)
//            val buffer = ByteArray(1024)
//            while (true){
//                val bytesRead = port.read(buffer, TIMEOUT)
//                Log.e("!!!bytesRead", ""+bytesRead)
//                if (bytesRead > 0) {
//                    val receivedData = buffer.copyOf(bytesRead)
//                    // 处理数据
//                    Log.e("!!!receivedData", String(receivedData, Charsets.UTF_8)+".."+bytesRead)
//                }
//            }
//
//        }
    }

    private fun registerUsbReceiver() {
        val filter = IntentFilter().apply {
//            addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
//            addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
            addAction(ACTION_USB_PERMISSION)
            addAction(ACTION_USB_PERMISSION2)
            addAction(INTENT_ACTION_GRANT_USB)
        }

        ContextCompat.registerReceiver(
            this,
            usbPermissionReceiver,
            filter,
            ContextCompat.RECEIVER_EXPORTED  // 需要接收系统广播
        )
    }

    private val usbReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            Log.e("usbReceiver",intent.action.toString() )
            when (intent.action) {
                UsbManager.ACTION_USB_DEVICE_ATTACHED -> {
                    usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
                    usbDevice?.let { requestPermission(it) }
                }
            }
        }
    }

    private val usbPermissionReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            Log.e("!!!intent.action", intent.action.toString())
            if (ACTION_USB_PERMISSION == intent.action) {
                synchronized(this) {
//                    val granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                    // 判断是否拥有权限
                    val hasPermission: Boolean = usbManager.hasPermission(usbDevice)
                    Log.e("!!!hasPermission",""+hasPermission)

                    val driver = CdcAcmSerialDriver(usbDevice)
                    val connection = usbManager.openDevice(driver.device)
////                    val connection = usbManager.openDevice(usbDevice)
                    Log.e("!!!connection",""+connection.toString())
//                    connection.close()
//                    return

                    //TEST
//                    val driver = CdcAcmSerialDriver(usbDevice)
                    val port = driver.ports.first() // 通常使用第一个端口
                    serialPort = port
                    port.open(connection)
                    port.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
                    val usbIoManager = SerialInputOutputManager(port, object: SerialInputOutputManager.Listener{
                        override fun onNewData(data: ByteArray) {
                            Log.e("!!!onNewData", String(data, Charsets.UTF_8))
                        }

                        override fun onRunError(e: Exception?) {
                            Log.e("!!!onRunError", e?.message.toString())
                        }

                    })
                    usbIoManager.start()
                    val data = """{"cmd":"sys_info"}"""
                    port.write(data.toByteArray(), 0);
                    Log.e("!!!port.write", data)
//                    val buffer = ByteArray(1024)
//                    val bytesRead = port.read(buffer, TIMEOUT)
//                    Log.e("!!!bytesRead", ""+bytesRead)
//                    if (bytesRead > 0) {
//                        val receivedData = buffer.copyOf(bytesRead)
//                        // 处理数据
//                        Log.e("receivedData", String(receivedData, Charsets.UTF_8)+".."+bytesRead)
//                    }
//                    port.close()
                }
            }
        }

    }



    private fun requestPermission(device: UsbDevice) {
        Log.e("device.deviceName", device.deviceName)
        val permissionIntent = PendingIntent.getBroadcast(
            this, 0, Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE
        )
        usbManager.requestPermission(device, permissionIntent)

    }

//    // 数据读写线程示例
//    private fun startIoThread() {
//        thread {
//            while (serialPort != null) {
//                try {
//                    // 接收数据
//                    val buffer = ByteArray(1024)
//                    val len = serialPort!!.read(buffer, 1000)
//                    if (len > 0) {
//                        val data = buffer.copyOf(len)
//                        runOnUiThread { updateUi(data) }
//                    }
//                } catch (e: IOException) {
//                    break
//                }
//            }
//        }
//    }
}
